package com.example.last.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.last.dao.*;
import com.example.last.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReservationService {
    @Resource
    private ReservationDao reservationDao;
    @Resource
    private DoctorDao doctorDao; //逻辑层实现多表关联
    @Resource
    private UserDao userDao;
    
    public PageInfo<Reservation> findBySearch(@Param("Params") Params params) {
        PageHelper.startPage(params.getPageNum(),params.getPageSize());

        List<Reservation> list =  reservationDao.findBySearch(params);
        if(CollectionUtil.isEmpty(list)){
            return PageInfo.of(new ArrayList<>());
        }
        for (Reservation Reservation : list){
            if(ObjectUtil.isNotEmpty(Reservation.getDoctorId())){
                Doctor doctor = doctorDao.selectByPrimaryKey(Reservation.getDoctorId());
                if(ObjectUtil.isNotEmpty(doctor)){
                    Reservation.setDoctorName(doctor.getUsername());
                }
            }
            if(ObjectUtil.isNotEmpty(Reservation.getUserId())){
                User user = userDao.selectByPrimaryKey(Reservation.getUserId());
                if(ObjectUtil.isNotEmpty(user)){
                    Reservation.setUserName(user.getName());
                }
            }
        }
        return PageInfo.of(list);
    }

    public void add(Reservation Reservation) {
        reservationDao.add(Reservation);
    }

    public void update(Reservation Reservation) {
        reservationDao.update(Reservation);
    }

    public void delete(Integer id) {
        reservationDao.delete(id);
    }
}
